package com.dean.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.dean.entity.DeanDbConnInfo;
import com.dean.entity.ExcelQueryResult;
import com.dean.listener.DeanEasyExcelListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * easy excel 异步工具类
 * @author Administrator
 *
 */
public class DeanEasyExcelUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(DeanEasyExcelUtils.class);
	
	/**
	 * 读取excel 所有sheet 名称
	 * @param filePath
	 * @return
	 */
	public static List<String> readSheetNames(String filePath) {
		List<String> sheetNames = new ArrayList<String>();
		// 读取sheet名称
		 List<ReadSheet> lists = EasyExcel.read(filePath).build().excelExecutor().sheetList();
		 lists.forEach(list -> {
			 sheetNames.add(list.getSheetName());
		 });
		 return sheetNames;
	}

	/**
	 * 保存excel内容到db
	 * @param fileName
	 * @param sheetName
	 */
	public static void saveSheetContent(String fileName, String sheetName, DeanEasyExcelListener deanEasyExcelListener){
		// 设置备注 用于导入数据库备用字段
		deanEasyExcelListener.setRemark(fileName+"##"+sheetName);
		EasyExcel.read(fileName,deanEasyExcelListener).sheet(sheetName).doRead();
	}

	
	/**
	 * 读取excel 所有sheet页内容
	 * @param fileName
	 * @return
	 */
	public static void saveAllSheetContent(String fileName, DeanEasyExcelListener deanEasyExcelListener){
		List<String> sheetNames = readSheetNames(fileName);
		for (String sheetName : sheetNames) {
			// 初始化返回信息
			try{
				saveSheetContent(fileName, sheetName, deanEasyExcelListener);
			}catch (Exception e){
				logger.error("保存excel内容出现异常,异常原因:{}",e.getMessage(),e);
			}
		}
		logger.info("文件:{}处理完成",fileName);

	}

	/**
	 * 写内容到excel
	 * @param outFilePath
	 * @param heads
	 * @param lists
	 */
	public static void writeExcel(String outFilePath,List<List<String>> heads,List<List<String>> lists) {
		EasyExcel.write(outFilePath).head(heads).sheet().doWrite(lists);
	}

	/**
	 * excel 文件写入
	 * @param outFilePath
	 * @param queryResult
	 */
	public static void writeExcel(String outFilePath, ExcelQueryResult queryResult) {
		EasyExcel.write(outFilePath).head(queryResult.getHeads()).sheet().doWrite(queryResult.getValues());
	}


	public static void writeExcel(ExcelWriter excelWriter, WriteSheet writeSheet, List<List<Object>> datas){
		excelWriter.write(datas,writeSheet);
	}
}
